package com.youoor.common.utils;

import javax.annotation.Resource;

import org.json.JSONException;
import org.springframework.stereotype.Component;

import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.PutPolicy;
import com.youoor.common.IdWorker;
import com.youoor.enums.ErrorCodeEnum;
import com.youoor.exception.ServiceException;
@Component
public class QiNiuUtils {

	    
	
	private static IdWorker idWorker;
	@Resource(name = "idWorker")
	public void setIdWorker(IdWorker idWorker) {
		this.idWorker = idWorker;
		
	}
	/**
	 * 七牛文件上传
	 * @param userId
	 * @param fileName
	 * @return
	 * @throws AuthException
	 * @throws JSONException
	 */
	public static String uploadFileToQiNiu(int userId,String fileName) throws AuthException, JSONException{
		Mac mac = new Mac(PropertiesUtil.getPropertySys("AccessKey"), PropertiesUtil.getPropertySys("SecretKey"));
		String bucketName = PropertiesUtil.getPropertySys("bucketName");
		PutPolicy putPolicy = new PutPolicy(bucketName);
	    String uptoken = putPolicy.token(mac);
	    PutExtra extra = new PutExtra();
	    String key = "youoor"+111122+".jpg";//文件名称idWorker.nextId()
//        String localFile = "C:/Users/guoxiaoliang/Desktop/6524.jpg";
        PutRet ret = IoApi.putFile(uptoken, key, fileName, extra);
        if(ret.getStatusCode() != 200){
        	throw new ServiceException(ErrorCodeEnum.CODE_YOUOOR_UPLOADFILE_ERROR);
        }
        return PropertiesUtil.getPropertySys("path_prefix")+key;
	}
	
	
	    public static void main(String[] args) throws Exception {
//
	        String localFile = "C:/Users/Administrator/Desktop/123.jpg";
	        //QiNiuUtils.uploadFileToQiNiu(1, localFile);
	        QiNiuUtils.getUpToken();
	        
	    }
	    
	    public static String getUpToken() {
	    	String accessKey = PropertiesUtil.getPropertySys("AccessKey");
	    	String secretKey = PropertiesUtil.getPropertySys("SecretKey");
	    	Mac mac = new Mac(accessKey, secretKey);
			String bucketName = PropertiesUtil.getPropertySys("bucketName");
			PutPolicy putPolicy = new PutPolicy(bucketName);
			String uptoken = null;
		    try {
				 uptoken = putPolicy.token(mac);
			} catch (AuthException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    return uptoken;
	    }
}
